package com.cdu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdu.enums.MessageEnum;
import com.cdu.mapper.TaskMapper;
import com.cdu.model.common.BaseResponse;
import com.cdu.model.common.PageResult;
import com.cdu.model.query.TaskQuery;
import com.cdu.model.query.UserQuery;
import com.cdu.pojo.Task;
import com.cdu.pojo.User;
import com.cdu.service.TaskService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: easy-help-v2
 * @description:
 * @author: hanabi
 * @create: 2022-05-17 10:14
 **/
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    private final TaskMapper taskMapper;

    //查询所有任务
    @Override
    public BaseResponse queryAllTask(TaskQuery taskQuery) {
        PageHelper.startPage(taskQuery.getPageNum(),taskQuery.getPageSize());
        String uidCreate = taskQuery.getUidCreate();
        String uidAccept = taskQuery.getUidAccept();
        String name = taskQuery.getName();
        Integer isUrgent = taskQuery.getIsUrgent();
        Date creatTime = taskQuery.getCreatTime();
        Date endTime = taskQuery.getEndTime();
        var taskWrapper = new LambdaQueryWrapper<Task>();
        if (creatTime==null && endTime==null){
            taskWrapper.like(StringUtils.isNotBlank(name),Task::getName,name)
                    .eq(isUrgent!=null,Task::getIsUrgent,isUrgent)
                    .eq(taskQuery.getIsDeal()!=null, Task::getIsDeal, taskQuery.getIsDeal())
                    .or().eq(StringUtils.isNotEmpty(uidCreate),Task::getCreator, uidCreate).or().eq(StringUtils.isNotEmpty(uidAccept),Task::getReceiveUserId,uidAccept);
        }else {
            taskWrapper.like(StringUtils.isNotBlank(name),Task::getName,name)
                    .and(i -> i.ge(creatTime!=null,Task::getCreateTime,creatTime)
                            .le(endTime!=null,Task::getDeadline,endTime))
                    .eq(isUrgent!=null,Task::getIsUrgent,isUrgent)
                    .eq(taskQuery.getIsDeal()!=null, Task::getIsDeal, taskQuery.getIsDeal())
                    .or().eq(StringUtils.isNotEmpty(uidCreate),Task::getCreator, uidCreate).or().eq(StringUtils.isNotEmpty(uidAccept),Task::getReceiveUserId,uidAccept);
        }

        List<Task> taskList = taskMapper.selectList(taskWrapper);
        var pageInfo = PageInfo.of(taskList);
        return BaseResponse.response(PageResult.doPage(pageInfo.getList(),
                pageInfo.getPageNum(),
                pageInfo.getPageSize(),
                pageInfo.getTotal()),
                MessageEnum.SUCCESS);

    }


    //查询任务by Id
    @Override
    public BaseResponse queryTaskById(TaskQuery taskQuery) {
        Task task = taskMapper.selectById(taskQuery.getId());
        return  BaseResponse.response(task,MessageEnum.SUCCESS);
    }

    //创建任务
    @Override
    public BaseResponse createTask(JSONObject ido) {
        Task task = new Task();
        String name = ido.getString("name");
        String content = ido.getString("content");
        String remark = ido.getString("remark");
        Double reward =  Double.valueOf(ido.getString("reward"));
        Date deadline = null;
        try {
            if (org.springframework.util.StringUtils.hasLength(ido.getString("deadline"))){
                deadline = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(ido.getString("deadline"));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer isUrgent =  Integer.valueOf(ido.getString("isUrgent"));
        String creator = ido.getString("creator");
        String imgUrl = ido.getString("imgUrl");

        task.setName(name);
        task.setContent(content);
        task.setRemark(remark);
        task.setReward(reward);
        task.setDeadline(deadline);
        task.setIsUrgent(isUrgent);
        task.setCreator(creator);
        task.setCreateTime(new Date());
        task.setIsDeal(0);
        task.setImgUrl(imgUrl);
        taskMapper.insert(task);
        return BaseResponse.response(MessageEnum.SUCCESS);
    }

    //修改任务
    @Override
    public BaseResponse updateTask(JSONObject ido) throws ParseException {
        String id = ido.getString("id");
        Task task = taskMapper.selectById(id);
        String name = ido.getString("name");
        String content = ido.getString("content");
        String remark = ido.getString("remark");
        Integer isdeal = Integer.valueOf(ido.getString("isDeal"));
        Double reward =  Double.valueOf(ido.getString("reward"));
        String modifier = ido.getString("modifier");
        Date deadline = null;
        try {
            if (org.springframework.util.StringUtils.hasLength(ido.getString("deadline"))){
                deadline = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(ido.getString("deadline"));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer isUrgent =  Integer.valueOf(ido.getString("isUrgent"));
        String creator = ido.getString("creator");
        String imgUrl = ido.getString("imgUrl");

        task.setName(name);
        task.setContent(content);
        task.setRemark(remark);
        task.setReward(reward);
        task.setDeadline(deadline);
        task.setIsUrgent(isUrgent);
        task.setCreator(creator);
        task.setIsDeal(isdeal);
        task.setImgUrl(imgUrl);
        task.setModifier(modifier);
        task.setUpdateUserId(modifier);
        task.setUpdateTime(new Date());
        taskMapper.updateById(task);
        return BaseResponse.response(MessageEnum.SUCCESS);
    }

    //接受任务
    @Override
    public BaseResponse acceptTask(JSONObject ido) {
        String tid = ido.getString("tid");
        String uid = ido.getString("uid");
        Task task = taskMapper.selectById(tid);
        if (task == null){
            return BaseResponse.response(MessageEnum.ERROR);
        }
        task.setReceiveUserId(uid);
        taskMapper.updateById(task);
        return BaseResponse.response(MessageEnum.SUCCESS);
    }

    //解决任务
    @Override
    public BaseResponse dealTask(JSONObject ido) {
        String tid = ido.getString("tid");
        String uid = ido.getString("uid");
        Task task = taskMapper.selectById(tid);
        if (task == null){
            return BaseResponse.response(MessageEnum.ERROR);
        }
        task.setUpdateUserId(uid);
        task.setIsDeal(1);
        taskMapper.updateById(task);
        return BaseResponse.response(MessageEnum.SUCCESS);
    }

    @Override
    public BaseResponse delTaskById(TaskQuery taskQuery) {
        Integer isdel=  taskMapper.deleteById(taskQuery.getId());
        if (isdel==1){
            return BaseResponse.response(MessageEnum.SUCCESS);
        }
        return BaseResponse.response(MessageEnum.ERROR);
    }
}

